#!/bin/bash
#
# Copyright 2011 Google Inc. All Rights Reserved.
# Author: sdd@google.com (Salvatore Domenick Desiano)
#
# Copies changes from the edit clone to the issue clone and uploads them to a
# Rietveld server for review. Only works properly if executed as part of a GLP
# checkout. See glp-common.sh for more information on the development process
# used by GLP developers.
#
# usage: src/scripts/glp-issue-create reviewer[,reviewer...] 'Issue description'
#        src/scripts/glp-issue-create none 'Issue description'


# Read parameters, initialize variables, and authenticate user.
source "$(dirname "$0")/glp-common.sh"
readonly reviewers="${1}"
readonly commit_message="${2}"
if [[ -z "${reviewers}" ]]; then
  glp::die "usage: $0 reviewers [message]"
fi
glp::initialize_checkout_variables "${new_edit_name}"
if [[ "${ISSUE_STATE}" != 'empty' ]]; then
  glp::die 'issue state must be empty'
fi
"${SCRIPT_DIR}/glp-issue-cache-password" "${RIETVELD_UPLOAD_SCRIPT}" \
  ${RIETVELD_PARAMS} || glp::die 'unable to cache Rietveld credentials'


if [[ ! -e "${ISSUE_CLONE}" ]]; then
  echo "Creating issue clone in ${ISSUE_CLONE}..."
  hg clone --quiet "${UPSTREAM_CLONE}" "${ISSUE_CLONE}"
  echo "default-push = ." >> "${ISSUE_CLONE}/.hg/hgrc"
fi


# Update the review clones from the upstream repository and edit
# clone.
echo 'Updating review clones...'
glp::update_review_clones 'new_issue_rev' "${commit_message}"


# Extract information (description, base revision) from review clones.
cd "${ISSUE_CLONE}"
hg log --rev "${new_issue_rev}" --template '{desc}' > \
    "${ISSUE_MESSAGE_PATH}" || \
  glp::die "Unable to extract message from ${new_issue_rev}."
cd - > /dev/null || glp::die 'failure.'
glp::read_file "${ISSUE_MESSAGE_PATH}" 'issue_message'
readonly issue_message
if [[ -z "${issue_message}" ]]; then
  glp::die "Unable to extract message from ${new_issue_rev}."
fi
echo "Calculating upstream base revision..."
glp::calculate_tip "${UPSTREAM_CLONE}" 'new_issue_base_rev'


# Create the issue.
echo "Creating issue against ${new_issue_base_rev}..."
cd "${ISSUE_CLONE}"
if [[ "${reviewers}" != 'none' ]]; then
    readonly reviewer_flag="--reviewers=${reviewers}"
fi
readonly new_issue_number="$("${RIETVELD_UPLOAD_SCRIPT}" ${RIETVELD_PARAMS} \
    ${reviewer_flag} --message="${issue_message}" \
    --rev="${new_issue_base_rev}" | \
  grep 'Issue created. URL: ' | \
  sed 's/^.*URL: //;s/ .*$//;s|^.*/||')"
if [[ -z "${new_issue_number}" ]]; then
  glp::die 'unable to create issue'
fi
cd - > /dev/null || glp::die "unable to cd out of ${ISSUE_CLONE}"


echo "Updating issue state..."
glp::write_issue_state 'active' ${new_issue_number} "${new_issue_base_rev}" \
    "${new_issue_rev}"
cat >> "${ISSUE_MESSAGE_PATH}" <<EOF


Rietveld review: ${RIETVELD_URL}/${new_issue_number}
EOF

echo "Issue ${new_issue_number} created."
